<template>
	<div class="metting">
		<header>
			<webHader :title="pageInfo.title" :crumbs="pageInfo.crumbs.join(',')" :backgroundImageUrl="headerBg" />
		</header>
		<div class="section">
			<div class="content">
				<div class="title">{{ pageInfo.title }}</div>
				<div class="form">
					<el-form ref="formRef" :model="formData" :rules="rules" label-position="left" class="application-form">
						<!-- 动态渲染字段 -->
						<template v-for="item in fields" :key="item.fieldCode">
							<el-form-item :label="item.fieldName" :prop="item.fieldCode"
								:class="item.inputType === 'upload' ? 'avatar-uploader' : ''"
								:label-width="getFieldProps(item).labelWidth || '100px'"
								:required="getFieldProps(item).required || item.required === 1" v-bind="getFieldItemProps(item)">
								<!-- 输入框 -->
								<el-input v-if="item.inputType === 'input'" v-model="formData[item.fieldCode]"
									:placeholder="item.tips || '请输入'" v-bind="getFieldProps(item)" />

								<!-- 数字输入 -->
								<el-input-number v-else-if="item.inputType === 'number'" v-model="formData[item.fieldCode]"
									v-bind="getFieldProps(item)" />

								<!-- 日期 -->
								<el-date-picker v-else-if="item.inputType === 'date'" v-model="formData[item.fieldCode]" type="date"
									:placeholder="item.tips || '请选择'" v-bind="getFieldProps(item)" />

								<!-- 下拉选择 -->
								<el-select v-else-if="item.inputType === 'select'" v-model="formData[item.fieldCode]"
									:placeholder="item.tips || '请选择'" v-bind="getFieldProps(item)">
									<el-option v-for="opt in getOptions(item)" :key="opt.value" :label="opt.label" :value="opt.value" />
								</el-select>

								<!-- 单选 -->
								<el-radio-group v-else-if="item.inputType === 'radio'" v-model="formData[item.fieldCode]"
									v-bind="getFieldProps(item)">
									<el-radio v-for="opt in getOptions(item)" :key="opt.value" :label="opt.value">
										{{ opt.label }}
									</el-radio>
								</el-radio-group>

								<!-- 级联 -->
								<el-cascader v-else-if="item.inputType === 'cascader'" v-model="formData[item.fieldCode]"
									:options="getOptions(item)" :placeholder="item.tips || '请选择'" v-bind="getFieldProps(item)" />

								<!-- 上传组件 -->
								<el-upload v-else-if="item.inputType === 'upload'" :on-change="file => onUploadChange(item, file)"
									:before-upload="file => beforeUpload(item, file)" :on-exceed="(files, fileList) => handleExceed(files, fileList, item)
										" v-bind="getUploadConfig(item)">
									<div :class="getUploadButtonClass(item)">
										<el-icon>
											<Plus />
										</el-icon>
										<div v-if="getUploadConfig(item).listType !== 'picture-card'">
											{{ getFieldProps(item).buttonText || '点击上传' }}
										</div>
									</div>
								</el-upload>
								<!-- 上传提示信息 -->
								<div v-if="getFieldProps(item).showTip && getFieldProps(item).tip" class="upload-tip">
									{{ getFieldProps(item).tip }}
								</div>
							</el-form-item>
						</template>
					</el-form>

					<el-row class="btns">
						<button @click="onSubmit" class="submit">提交</button>
						<!-- <button @click="onSave" class="save">保存</button> -->
					</el-row>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import headerBg from '~/assets/web/activity-header-bg.png';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { GetListOfRegistrationForms, GetInfoFormByUserId, SubmitRealtimeinfoUserCustom } from '~/apis/web';
import { userStore } from '~/composables/store/modules/user';

// 路由参数
const router = useRouter();
const route = useRoute();
const id = route.query.id;
const formId = route.query.formId;
const store = userStore();

// 表单
const formRef = ref(null);
const formData = reactive({});
const previewMap = reactive({}); // 上传预览
const rules = reactive({});
const fields = ref([]); // 动态字段（已按 sort 排序）
const pageInfo = ref({ title: '', crumbs: ['主页'] })

// 安全解析 JSON
const parseJSON = (str, fallback) => {
	if (!str) return fallback;
	try {
		const v = typeof str === 'string' ? JSON.parse(str) : str;
		return v ?? fallback;
	} catch (e) {
		return fallback;
	}
};

// 直接透传 fieldJson 的所有属性到组件
const getFieldProps = item => {
	return parseJSON(item?.fieldJson, {}) || {};
};

// 获取表单项的属性（label 相关）
const getFieldItemProps = item => {
	const props = parseJSON(item?.fieldJson, {}) || {};
	const itemProps = {};

	// 提取表单项相关的属性
	if (props.labelWidth) itemProps['label-width'] = props.labelWidth;
	if (props.labelPosition) itemProps['label-position'] = props.labelPosition;
	if (props.labelClass) itemProps['label-class-name'] = props.labelClass;
	if (props.span) itemProps.span = props.span;
	if (props.layout) itemProps.layout = props.layout;

	return itemProps;
};

// 解析选项
const getOptions = item => {
	const opts = parseJSON(item?.fieldOption, []);
	return Array.isArray(opts) ? opts : [];
};

// 规范化默认值：优先使用 formValue，其次使用 fieldJson 中的 defaultValue
const normalizeDefaultValue = item => {
	const t = item?.inputType;
	let v = item?.formValue;

	// 如果 formValue 为空，尝试使用 fieldJson 中的 defaultValue
	if (v === undefined || v === null || v === '') {
		const fieldProps = parseJSON(item?.fieldJson, {});
		if (fieldProps?.defaultValue !== undefined) {
			v = fieldProps.defaultValue;
		}
	}

	// 若表单值是字符串但目标应为复杂类型，尝试解析
	if (
		(t === 'cascader' || t === 'upload' || t === 'select' || t === 'radio') &&
		typeof v === 'string'
	) {
		const parsed = parseJSON(v, v);
		v = parsed;
	}

	if (v !== undefined && v !== null && v !== '') {
		if (t === 'number') {
			const n = Number(v);
			return Number.isNaN(n) ? null : n;
		}

		// 对于 radio 类型，检查默认值是否在选项中
		if (t === 'radio') {
			const options = getOptions(item);
			const optionValues = options.map(opt => opt.value);
			// 如果默认值不在选项中，返回空字符串以触发校验
			if (!optionValues.includes(v)) {
				return '';
			}
		}
		return v;
	}

	// 无 formValue 和 defaultValue 则按类型给默认
	switch (t) {
		case 'number':
			return null;
		case 'cascader':
			return [];
		case 'upload':
			return '';
		case 'radio':
			return ''; // radio 类型返回空字符串以触发校验
		default:
			return '';
	}
};

// 构建表单模型与规则
const buildForm = list => {
	const sorted = [...(list || [])].sort((a, b) => (a?.sort ?? 0) - (b?.sort ?? 0));
	fields.value = sorted;

	const nextModel = {};
	const nextRules = {};

	sorted.forEach(item => {
		const code = item.fieldCode;

		// 默认值：优先表单已有 formValue
		nextModel[code] = normalizeDefaultValue(item);
		const required = getFieldProps(item).required == true;
		const rls = [];
		if (required) {
			const msgMap = {
				input: `请输入${item.fieldName}`,
				number: `请输入${item.fieldName}`,
				upload: `请上传${item.fieldName}`,
			};
			const msg = msgMap[item.inputType] || `请选择${item.fieldName}`;
			// 如果有 tips，优先使用 tips 作为错误提示
			const finalMsg = item?.tips || msg;
			const trigger =
				item.inputType === 'input' ||
					item.inputType === 'number' ||
					item.inputType === 'upload'
					? 'blur'
					: 'change';
			rls.push({ required: true, message: finalMsg, trigger });
		}

		// 常用额外校验
		if (code === 'email') {
			rls.push({
				type: 'email',
				message: '请输入正确的邮箱格式',
				trigger: 'blur',
			});
		}
		if (code === 'mobile') {
			rls.push({
				pattern: /^1[3-9]\d{9}$/,
				message: '请输入正确的手机号码',
				trigger: 'blur',
			});
		}

		nextRules[code] = rls;
	});

	// 覆盖到响应式对象
	Object.keys(formData).forEach(k => delete formData[k]);
	Object.assign(formData, nextModel);

	Object.keys(rules).forEach(k => delete rules[k]);
	Object.assign(rules, nextRules);

	// 初始化上传预览（如果默认是 URL）
	sorted.forEach(item => {
		if (item.inputType === 'upload') {
			const code = item.fieldCode;
			const v = formData[code];
			if (typeof v === 'string' && v) {
				previewMap[code] = v;
			}
		}
	});
};

// 上传改变（本地预览 + 保存原始文件/或 URL）
const onUploadChange = (item, file) => {
	const raw = file?.raw;
	const code = item.fieldCode;
	if (raw) {
		previewMap[code] = URL.createObjectURL(raw);
		// 不要直接设置 formData，等待上传成功后再设置ID
		// formData[code] = raw; // 注释掉这行
	} else if (file?.url) {
		previewMap[code] = file.url;
		// 如果已经有URL，说明可能是编辑模式，直接使用URL作为ID
		formData[code] = file.url;
	}
};

// 文件上传成功后的处理
const onUploadSuccess = (item, response, file) => {
	const code = item.fieldCode;
	const fieldProps = getFieldProps(item);
	// 根据实际接口返回格式调整
	let fileId = null;
	// 尝试多种可能的响应格式
	if (response?.code === 0) {
		if (response?.data?.id) {
			fileId = response.data.id;
		} else if (response?.data?.fileId) {
			fileId = response.data.fileId;
		} else if (response?.data?.url) {
			fileId = response.data.url;
		} else if (typeof response?.data === 'string') {
			fileId = response.data;
		}
	} else if (response?.id) {
		fileId = response.id;
	} else if (response?.fileId) {
		fileId = response.fileId;
	} else if (response?.url) {
		fileId = response.url;
	}

	if (fileId) {
		if (fieldProps.multiple) {
			// 多文件上传：将ID添加到现有ID列表中
			const currentIds = formData[code] ? formData[code].split(',').filter(id => id) : [];
			currentIds.push(fileId);
			formData[code] = currentIds.join(',');
		} else {
			// 单文件上传：直接设置ID
			formData[code] = fileId;
		}
	} else {
		ElMessage.error('文件上传成功但无法获取文件ID');
	}
};

// 文件上传失败的处理
const onUploadError = (item, error, file) => {
	ElMessage.error('文件上传失败，请重试');

	// 上传失败时清空对应的formData
	const code = item.fieldCode;
	const fieldProps = getFieldProps(item);
	if (!fieldProps.multiple) {
		formData[code] = '';
	}
};

// 文件移除的处理
const onRemove = (item, file) => {
	const code = item.fieldCode;
	const fieldProps = getFieldProps(item);

	if (fieldProps.multiple && formData[code]) {
		// 多文件：从ID列表中移除对应的ID
		// 这里需要根据文件名或其他标识来匹配要移除的ID
		// 由于Element Plus的上传组件限制，可能需要维护一个文件到ID的映射
	} else {
		// 单文件：清空ID
		formData[code] = '';
	}

	// 清除预览
	if (previewMap[code]) {
		URL.revokeObjectURL(previewMap[code]);
		delete previewMap[code];
	}
};

// 文件超出限制处理
const handleExceed = (files, fileList, item) => {
	const fieldProps = getFieldProps(item);
	const maxFiles = fieldProps.multiple ? '多个' : '1个';
	ElMessage.warning(`最多只能上传 ${maxFiles} 文件`);
};

// 文件上传前的验证（增强版，支持 regList）
const beforeUpload = (item, file) => {
	const fieldProps = getFieldProps(item);

	// 1. 文件大小验证
	const fileSize = fieldProps.fileSize;
	const sizeUnit = fieldProps.sizeUnit;

	if (fileSize && sizeUnit) {
		let maxSizeInBytes;
		switch (sizeUnit.toLowerCase()) {
			case 'kb':
				maxSizeInBytes = fileSize * 1024;
				break;
			case 'mb':
				maxSizeInBytes = fileSize * 1024 * 1024;
				break;
			case 'gb':
				maxSizeInBytes = fileSize * 1024 * 1024 * 1024;
				break;
			default:
				maxSizeInBytes = fileSize;
		}

		if (file.size > maxSizeInBytes) {
			ElMessage.error(`文件大小不能超过 ${fileSize}${sizeUnit}`);
			return false;
		}
	}

	// 2. 文件类型验证（regList）
	const regList = fieldProps.regList || [];
	if (regList.length > 0) {
		const fileName = file.name;
		const isValidType = regList.some(reg => {
			if (typeof reg === 'string') {
				// 字符串格式：直接匹配文件扩展名
				return fileName.toLowerCase().endsWith(reg.toLowerCase());
			} else if (reg && typeof reg === 'object') {
				// 对象格式：支持更复杂的验证规则
				if (reg.pattern) {
					return new RegExp(reg.pattern).test(fileName);
				}
				if (reg.extensions) {
					return reg.extensions.some(ext =>
						fileName.toLowerCase().endsWith(ext.toLowerCase())
					);
				}
			}
			return false;
		});

		if (!isValidType) {
			const allowedTypes = regList
				.map(reg =>
					typeof reg === 'string'
						? reg
						: reg.extensions
							? reg.extensions.join(', ')
							: reg.pattern
				)
				.join(', ');
			ElMessage.error(`文件类型不支持，仅支持：${allowedTypes}`);
			return false;
		}
	}

	return true;
};

// 在 script setup 中添加新的计算属性
const getUploadConfig = item => {
	const fieldProps = getFieldProps(item);
	const listType = fieldProps.listType || 'text';

	return {
		...fieldProps,
		listType,
		showFileList: fieldProps.showFileList !== undefined ? fieldProps.showFileList : true,
		multiple: fieldProps.multiple || false,
		limit: fieldProps.multiple ? fieldProps.limit || 10 : 1,
		// 确保 disabled 属性正确传递
		disabled: fieldProps.disabled || false,
		// 添加上传成功和失败的回调
		'on-success': (response, file) => onUploadSuccess(item, response, file),
		'on-error': (error, file) => onUploadError(item, error, file),
		'on-remove': file => onRemove(item, file),
		// 如果需要自动上传，确保有action属性
		action: fieldProps.action || '/api/upload', // 根据实际接口调整
		'auto-upload': fieldProps.autoUpload !== false, // 默认自动上传
	};
};

// 简化后的按钮样式方法
const getUploadButtonClass = item => {
	const listType = getUploadConfig(item).listType;
	const baseClass = 'upload-placeholder';

	const styleMap = {
		'picture-card': `${baseClass} picture-card-style`,
		picture: `${baseClass} picture-style`,
		text: baseClass,
	};

	return styleMap[listType] || baseClass;
};

const onSubmit = async () => {
	if (!formRef.value) return;
	await formRef.value.validate(async valid => {
		if (valid) {
			// 整理为 { fieldCode, formValue } 列表
			const payload = fields.value.map(item => ({
				...item,
				formValue: formData[item.fieldCode],
			}));
			const data = {
				realtimeinfoId: id,
				userId: store.user.id,
				customTableId: formId,
				detailList: payload
			}
			// 打印提交内容
			await SubmitRealtimeinfoUserCustom(data);
			router.back();
			ElMessage.success('提交成功');
		} else {
			ElMessage.error('请填写完整所有必填项');
		}
	});
};

// const onSave = async () => {
// 	if (!formRef.value) return;
// 	const payload = fields.value.map(item => ({
// 		fieldCode: item.fieldCode,
// 		formValue: formData[item.fieldCode],
// 	}));

// 	// 打印保存内容

// 	// : 调用保存API，提交 { id, list: payload }
// 	ElMessage.success('保存成功');
// };

// 初始化：获取字段配置
const init = async () => {
	try {
		const { code, data } = await GetListOfRegistrationForms(formId);
		if (code === 0) {
			const list = data?.detailDTOList || [];
			buildForm(list);
			pageInfo.value = {
				title: data?.name,
				crumbs: pageInfo.value.crumbs.concat(data?.name),
			}
		} else {
			buildForm([]);
		}
	} catch (err) {
		buildForm([]);
	}
};

onMounted(() => {
	init();
});
</script>

<style lang="less" scoped>
.metting {
	background-color: #f5f5f5;
	width: 100%;

	.section {
		width: 100%;
		padding: 30px 104px;
		margin-bottom: 70px;
		box-sizing: border-box;

		.content {
			width: 100%;
			background-color: #ffffff;
			padding: 30px 50px;

			.title {
				font-family: PingFang HK, PingFang HK;
				font-weight: 500;
				font-size: 30px;
				color: #1e2021;
				text-align: left;
				font-style: normal;
				text-transform: none;
				margin-bottom: 30px;
			}

			.form {
				.application-form {
					margin-left: 0;

					:deep(.el-form-item__label) {
						font-family: PingFang HK, PingFang HK;
						font-weight: 400;
						font-size: 16px;
						color: #1e2021;
						text-align: left;
						display: block;
						margin-bottom: 10px;
						padding-bottom: 0;
						line-height: 1.4;
					}

					:deep(.el-form-item__content) {
						margin-left: 0 !important;
						width: 100%;
					}

					/* 完全重新创建的上传组件样式 */
					/* 1. 移除 Element Plus 的默认样式 */
					:deep(.el-upload) {
						border: none !important;
						background: none !important;
						width: auto !important;
						height: auto !important;
					}

					:deep(.el-upload-dragger) {
						border: none !important;
						background: none !important;
						width: auto !important;
						height: auto !important;
					}

					/* 禁用状态下的上传组件 */
					:deep(.el-upload.is-disabled) {
						cursor: not-allowed;
					}

					:deep(.el-upload.is-disabled .upload-placeholder) {
						background-color: #f5f5f5 !important;
						border: 1px solid #e4e7ed !important;
						/* 改为实线边框 */
						cursor: not-allowed !important;
						opacity: 0.6;
					}

					:deep(.el-upload.is-disabled .upload-placeholder:hover) {
						background-color: #f5f5f5 !important;
						border: 1px solid #e4e7ed !important;
						/* 确保hover时也是实线 */
					}

					:deep(.el-upload.is-disabled .upload-placeholder .el-icon) {
						color: #c0c4cc !important;
					}

					:deep(.el-upload.is-disabled .upload-placeholder div) {
						color: #c0c4cc !important;
					}

					:deep(.el-upload-list) {
						margin-top: 8px;
					}

					:deep(.el-upload-list__item) {
						background: #f5f7fa;
						border: 1px solid #e4e7ed;
						border-radius: 4px;
						padding: 8px 12px;
						margin-bottom: 4px;
						display: flex;
						align-items: center;
						justify-content: space-between;
					}

					:deep(.el-upload-list__item-name) {
						color: #606266;
						font-size: 14px;
						margin-right: 50px;
						flex: 1;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					:deep(.el-upload-list__item-actions) {
						position: absolute;
						right: 8px;
						top: 50%;
						transform: translateY(-50%);
					}

					:deep(.el-upload-list__item-delete) {
						color: #f56c6c;
						font-size: 16px;
						cursor: pointer;
						padding: 0;
						margin: 0;
					}

					/* 2. 自定义上传按钮样式 */
					.upload-placeholder {
						background-color: #fafafa;
						border: 1px dashed #d9d9d9;
						border-radius: 6px;
						padding: 20px;
						width: 130px !important;
						/* 固定宽度130px */
						height: 130px !important;
						/* 固定高度130px */
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						cursor: pointer;
						transition: all 0.3s ease;
						box-sizing: border-box;
						/* 移除 min-width 和 min-height，使用固定尺寸 */
					}

					.upload-placeholder:hover {
						background-color: #f0f9ff;
						border-color: #409eff;
					}

					.upload-placeholder .el-icon {
						font-size: 24px;
						color: #999;
						margin-bottom: 8px;
					}

					.upload-placeholder div {
						font-family: PingFang HK, PingFang HK;
						font-weight: 400;
						font-size: 14px;
						color: #666;
						line-height: 1.4;
					}

					/* 3. 上传提示信息样式 */
					.upload-tip {
						margin-top: 8px;
						font-family: PingFang HK, PingFang HK;
						font-weight: 400;
						font-size: 14px;
						color: #999;
						line-height: 1.4;
						text-align: left;
					}

					/* 4. 其他表单组件样式保持不变 */
					:deep(.el-input),
					:deep(.el-select),
					:deep(.el-input__wrapper),
					:deep(.el-select .el-input__wrapper),
					:deep(.el-cascader .el-input__wrapper),
					:deep(.el-input-number) {
						width: 484px !important;
						box-sizing: border-box;
					}

					/* 5. 修改表单项布局为左右布局 */
					// :deep(.el-form-item) {
					//   flex-direction: row !important; /* 改为左右布局 */
					//   align-items: center !important; /* 垂直居中对齐 */
					//   margin-bottom: 20px;
					// }

					:deep(.el-form-item__label) {
						width: auto !important;
						/* 标签宽度自适应 */
						min-width: 100px;
						/* 设置最小宽度 */
						padding-right: 12px !important;
						/* 标签右边距 */
						line-height: 32px !important;
						/* 标签行高 */
						box-sizing: border-box;
					}

					:deep(.el-form-item__content) {
						flex: 1;
						/* 内容区域占据剩余空间 */
						display: flex;
						align-items: center;
					}

					/* 6. 特殊处理上传组件的布局（保持上下布局） */
					:deep(.el-form-item:has(.el-upload)) {
						flex-direction: column !important;
						/* 上传组件保持上下布局 */
						align-items: flex-start !important;
					}

					:deep(.el-form-item:has(.el-upload) .el-form-item__label) {
						text-align: left !important;
						/* 上传组件的标签左对齐 */
						padding-right: 0 !important;
						margin-bottom: 8px;
					}

					:deep(.el-form-item:has(.el-upload) .el-form-item__content) {
						width: 100%;
					}

					:deep(.el-row) {
						.el-select {
							width: 306px !important;
						}
					}

					:deep(.el-input__inner::placeholder) {
						font-family: PingFang HK, PingFang HK;
						font-weight: 400;
						font-size: 16px;
						color: #999999;
						text-align: left;
					}

					:deep(.el-input__inner) {
						font-family: PingFang HK, PingFang HK;
						font-weight: 400;
						font-size: 16px;
						color: #1e2021;
						text-align: left;
					}

					:deep(.el-input__wrapper input) {
						font-size: 16px;
					}

					:deep(.el-select__selected-item span) {
						font-family: PingFang HK, PingFang HK;
						font-weight: 400;
						font-size: 16px;
						color: #1e2021;
						text-align: left;
					}

					:deep(.is-transparent span) {
						font-family: PingFang HK, PingFang HK;
						font-weight: 400;
						font-size: 16px;
						color: #999999;
						text-align: left;
					}

					// :deep(.el-form-item) {
					//   align-items: flex-start;
					//   flex-direction: column;
					// }
				}

				.btns {
					margin-top: 50px;
					width: 100%;

					button {
						padding: 15px 65px;
						box-sizing: border-box;
						border-radius: 0px 0px 0px 0px;
						border: 1px solid #1e2021;
						cursor: pointer;
						font-family: PingFang HK, PingFang HK;
						font-weight: 500;
						font-size: 16px;
						color: #1e2021;
					}

					.submit {
						margin-right: 20px;
						background: var(--theme-gradient-bg);
						border: none;
						color: #ffffff;
					}
				}

				:deep(.el-form-item--default) {
					margin-bottom: 20px;
				}

				.form-title {
					font-family: PingFang HK, PingFang HK;
					font-weight: 400;
					font-size: 16px;
					color: #1e2021;
					text-align: left;
					margin-bottom: 20px;
				}
			}
		}
	}
}

:deep(.el-radio.is-checked .el-radio__inner) {
	border-color: #226f41 !important;
	background-color: #fff !important;
}

:deep(.el-radio.is-checked .el-radio__inner::after) {
	width: 8px !important;
	height: 8px !important;
	background-color: #226f41 !important;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
}

:deep(.el-radio.is-checked .el-radio__label) {
	color: #226f41 !important;
}
</style>
